<?php

class route {
	function __construct($args) {
		$this->url = $args['url'];
		if(isset($args['set'])) {
			$this->set = $args['set'];
		} else {
			$this->set = array();
		}
		$this->plugin = $args['plugin'];
	}
	
	function check($url, $routeVars) {
		$regex = '|(?<!.)'.$this->url.'/(?!.)|';
		foreach($routeVars as $rv) {
			$regex = str_replace($rv['identifier'],'(?P<'.$rv['name'].'>'.$rv['regex'].')',$regex);
		}
		preg_match_all($regex, $url, $matches);
		if($matches[0]==array())
			return false;
		$vars = array();
		foreach($matches as $key=>$match) {
			if(!is_int($key))
				$vars[$key] = $match[0];
		}
		foreach($this->set as $varName=>$value) {
			$vars[$varName] = $value;
		}
		return $vars;
	}

	function getPlugin() {
		return $this->plugin;
	}
};

class routeHandler {
	var $routes = array();
	var $curRoute = 0;
	var $routeVars = array();
	var $curRouteVar = 0;
	
	function __construct($cli, $plugins) {
		$this->cli = $cli;
		$regex = '';
		foreach($plugins as $plugin) {
			$regex .= $plugin;
			if($regex!=$plugin) {
				$regex .= '|';
			}
		}
		$this->newRouteVar(array('name'=>'plugin','identifier'=>':plugin:','regex'=>$regex));
		$this->load('core/config/routes.yml');
		$this->load('app/config/routes.yml');
		foreach($plugins as $plugin) {
			$this->load('plugins/'.$plugin.'/config/routes.yml');
		}
	}

	function load($filename, $plugin = null) {
		if(!file_exists($filename)) {
			return false;
		}
		$data = spyc::YAMLLoad($filename);
		if(isset($data['routeVars'])) {
			foreach($data['routeVars'] as $routeVar) {
				if($routeVar['regex']=='default') {
					$routeVar['regex'] = AETHER_REGEX_DIR;
				}
				$this->newRouteVar($routeVar);
			}
		}
		foreach($data['routes'] as $route) {
			$route['plugin'] = $plugin;
			if($route['mode']=='cli') {
				$route['mode'] = AETHER_CLI;
			} else if($route['mode']=='both') {
				$route['mode'] = AETHER_BOTH;
			} else {
				$route['mode'] = AETHER_WEB;
			}
			$this->newRoute($route);
		}
	}
	
	function newRoute($args) {
		if($args['mode']==AETHER_BOTH||$args['mode']==$this->cli) {
			$this->routes[$this->curRoute] = new route($args);
			$this->curRoute++;
		}
	}
	
	function newRouteVar($args) {
		$this->routeVars[$this->curRouteVar] = $args;
		$this->curRouteVar++;
	}
	
	function checkRoutes($url) {
		foreach($this->routes as $route) {
			$plugin = $route->getPlugin();
			$routeVars = $this->routeVars;
			if($plugin) {
				$routeVars = arrayAppend($routeVars, array(array('name'=>'plugin', 'identifier'=>':this:', 'regex'=>$plugin)));
			}
			if($vars = $route->check($url, $routeVars)) {
				return $vars;
			}
		}
		return false;
	}
}

//EOF
